package com.dcjt.firehotcarpad.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Typeface
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProviders
import com.allen.library.SuperTextView
import com.amap.api.maps.AMap
import com.amap.api.maps.model.Marker
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.retrofit.FastObserver
import com.aries.library.fast.util.FastStackUtil
import com.aries.library.fast.util.SizeUtil
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.radius.RadiusTextView
import com.bumptech.glide.Glide
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.R2.id.text
import com.dcjt.firehotcarpad.fragment.CarEntity
import com.dcjt.firehotcarpad.fragment.WaterSourceEntity
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.model.HandleDisasterViewModel
import com.dcjt.firehotcarpad.moudle.HandleDisasterActivity
import com.dcjt.firehotcarpad.moudle.NavActivity
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1
import com.dcjt.firehotcarpad.utils.AlertDialogUtil
import com.dcjt.firehotcarpad.utils.StringUtils
import com.google.gson.Gson
import com.trello.rxlifecycle2.android.ActivityEvent
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import java.util.zip.DataFormatException

/**
 * Created by cj on 2021/2/23.
 * Email:codesexy@163.com
 * Function:
 * desc:
 */
class MapWindowInfoAdapter : AMap.InfoWindowAdapter {

    override fun getInfoWindow(marker: Marker?): View {
        var infoWindow = LayoutInflater.from(FastStackUtil.getInstance().current)
            .inflate(R.layout.layout_map_marker_info, null)
        marker?.let { renderInfo(it, infoWindow) }
        return infoWindow
    }



    private fun renderInfo(marker: Marker, infoWindow: View) {
        val name = infoWindow.findViewById<SuperTextView>(R.id.stvName)
        val address = infoWindow.findViewById<SuperTextView>(R.id.stvAddress)
        val sourceType = infoWindow.findViewById<SuperTextView>(R.id.stvSourceType)
        val getType = infoWindow.findViewById<SuperTextView>(R.id.stvGetType)
        val icClose = infoWindow.findViewById<ImageView>(R.id.ivClose)
        val ll_img = infoWindow.findViewById<LinearLayout>(R.id.ll_img)
        val ll_car = infoWindow.findViewById<LinearLayout>(R.id.ll_car)
        val stv_gj = infoWindow.findViewById<SuperTextView>(R.id.stv_gj)
        val stv_sy = infoWindow.findViewById<SuperTextView>(R.id.stv_sy)
        val st_ll = infoWindow.findViewById<SuperTextView>(R.id.st_ll)
        icClose.setOnClickListener { marker.hideInfoWindow() }

        val sourceEntity = marker.`object` as WaterSourceEntity

        //动态添加图片
        addWaterImage(sourceEntity.fwtb as String?, ll_img,"方位图北")
        addWaterImage(sourceEntity.fwtd as String?, ll_img,"方位图东")
        addWaterImage(sourceEntity.fwtn as String?, ll_img,"方位图南")
        addWaterImage(sourceEntity.fwtx as String?, ll_img,"方位图西")

        if (sourceEntity.cldata!= null && sourceEntity.cldata.size >0){
            //车辆数据
            addTextMsTitle(ll_car,"共有${ sourceEntity.cldata.size.toString()}辆车使用该水源:")
            sourceEntity.cldata.forEach {
                addTextCarInfo(ll_car,it)
//                addLineView(ll_car)
            }

        }


        name.setCenterString(sourceEntity.symc ?: "未知")
        address.setCenterString(sourceEntity.sydz ?: "未知")
        sourceType.setCenterString(sourceEntity.sylxmc ?: "未知")
        getType.setCenterString(sourceEntity.qsxs ?: "未知")

        stv_gj.setCenterString("${StringUtils.getNoNullString(sourceEntity.zj.toString(),"0")}mm")
        stv_sy.setCenterString("${StringUtils.getNoNullString(sourceEntity.yl.toString(),"0")}Mpa")
        st_ll.setCenterString("${StringUtils.getNoNullString(sourceEntity.ll.toString(),"0")}L/S")

        val lon = sourceEntity.gisX
        val lat = sourceEntity.gisY

        var editWater = infoWindow.findViewById<RadiusTextView>(R.id.rtv_zlsy)
        if (FastStackUtil.getInstance().current.javaClass == HandleDisasterActivity::class.java){
            editWater?.visibility = View.VISIBLE
        } else{
            editWater?.visibility = View.GONE
        }
        editWater.setOnClickListener {
            val map = HashMap<String, Any>()
            map["syid"] = sourceEntity.id!!
            map["zqid"] = CarStatePool.get().getCurrentZqidPage()!!
            map["clid"] = DataManager.getInstance().user.account
            ApiRepository1.getInstance()
                .uploadWaterZLSY(AlertDialogUtil.createBody(hashMapOf(Pair("data", Gson().toJson(map)))))
                .compose((FastStackUtil.getInstance().current as RxAppCompatActivity).bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(object : FastObserver<Any>() {
                    override fun _onNext(entity: Any) {
                        LoggerManager.e(entity.toString())
                        ToastUtil.show("成功占领水源")
                    }

                    override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                        super._onError(errorRes, errorCode, e)
                        if (e is DataFormatException) {
                            ToastUtil.show("成功占领水源")
                           var handleViewModel =
                                ViewModelProviders.of(FastStackUtil.getInstance().current as FragmentActivity).get(HandleDisasterViewModel::class.java)
                            handleViewModel.loadDisasterDetail(CarStatePool.get().getCurrentZqidPage()!!)
                            //刷新水源列表
                            LocationPool.get().onRefreshWaterListDispatch()

                        } else{
                            ToastUtil.show("占领失败")
                        }
                        LoggerManager.e(e.message)

                    }

                })
        }
        infoWindow.findViewById<RadiusTextView>(R.id.nav).setOnClickListener {
            try {
                val lon = lon?.toBigDecimal()?.toDouble()
                val lat = lat?.toBigDecimal()?.toDouble()
                if (lon != null && lat != null)
                    NavActivity.startNavActivity(
                        FastStackUtil.getInstance().current,
                        lat,
                        lon
                    )

            } catch (e: Exception) {
                e.printStackTrace()
                ToastUtil.show("该点位数据格式错误")
            }
        }


    }

    private fun addTextCarInfo(ll_view: LinearLayout,it: CarEntity) {
        var text = TextView(FastStackUtil.getInstance().current)
        text.setText("${it.cljc} ${it.cphm}(${it.deptName})")
        text.textSize = 14.0f
        var params_text = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)
        text.setGravity(Gravity.LEFT);
        //在获取LayoutParams之前要设置LayoutParams 否则会空指针异常
        params_text.setMargins(0, 10, 0, 10);
        text.setTextColor(Color.parseColor("#333333"))
        ll_view.addView(text, params_text);
    }
    @SuppressLint("ResourceType")
    private fun addLineView(ll_view: LinearLayout) {
        var view = View(FastStackUtil.getInstance().current)
        var params_text = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,1)
        view.setBackgroundResource(FastStackUtil.getInstance().current.resources.getColor(R.color.line))
        //在获取LayoutParams之前要设置LayoutParams 否则会空指针异常
        params_text.setMargins(0, 10, 0, 10);
        ll_view.addView(view, params_text);
    }

    private fun addTextMsTitle(ll_view: LinearLayout, str :String) {
        var text = TextView(FastStackUtil.getInstance().current)
        text.setText(str)
        text.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//加粗
        text.textSize =16f
        var params_text = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)
        text.setGravity(Gravity.LEFT);
        text.setTextColor(Color.parseColor("#191919"))
        ll_view.addView(text, params_text);
    }

    private fun addWaterImage(
        url: String?,
        ll_view: LinearLayout,
        ms: String?
    ) {
        if (StringUtils.isEmpty(url)){
            return
        }
        var ll_img = LinearLayout(FastStackUtil.getInstance().current)
        ll_img.orientation = LinearLayout.VERTICAL
        var params_ll = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)

        var imageView = ImageView(FastStackUtil.getInstance().current);
        var params_img = LinearLayout.LayoutParams(
            SizeUtil.dp2px(70.0f),
            SizeUtil.dp2px(70.0f)
        )
        params_img.marginStart = SizeUtil.dp2px(7.0f);

        Glide.with(FastStackUtil.getInstance().current)
            .load(DataManager.getInstance().appConfigEntity.appServerUrl.logUrl + "/" +url )
            .into(imageView)
        ll_img.addView(imageView, params_img)

        var text = TextView(FastStackUtil.getInstance().current)
        text.setText(ms)
        text.textSize = 10.0f
        var params_text = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)
        text.setGravity(Gravity.CENTER);
        ll_img.addView(text, params_text)

        ll_view.addView(ll_img, params_ll);
    }

    override fun getInfoContents(marker: Marker?): View? = null


}